package com.michale.common.utils.security;

import com.michale.common.codemessage.HTTPCodeMessage;
import com.michale.common.constants.UserConstant;
import com.michale.common.domain.permissions.RoleEntity;
import com.michale.common.domain.security.LoginUserDetail;
import com.michale.common.exception.ServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.Comparator;

import static com.michale.common.constants.SecurityConstant.*;

/**
 * @author Michale
 * @apiNote 安全服务工具类
 */
public class SecurityUtils {
    /**
     * 用户ID
     **/
    public static Long getUserId() {
        try {
            return getLoginUser().getUserId();
        } catch (Exception e) {
            throw new ServiceException(SECURITY_UTILS, SECURITY_UTILS_GET_USER_ID, HTTPCodeMessage.UNAUTHORIZED.getCode());
        }
    }

    /**
     * 用户身份标识
     **/
    public static String getUserIdentity() {
        try {
            return SecurityUtils.getLoginUser().getUserEntity().getRoleEntityList()
                    .stream().min(Comparator.comparing(RoleEntity::getIdentity)).get().getIdentity();
        } catch (Exception e) {
            throw new ServiceException(SECURITY_UTILS, SECURITY_UTILS_GET_USER_IDENTITY, HTTPCodeMessage.UNAUTHORIZED.getCode());
        }
    }

    /**
     * 获取部门ID
     **/
    public static Long getDeptId() {
        try {
            return getLoginUser().getDeptId();
        } catch (Exception e) {
            throw new ServiceException(SECURITY_UTILS, SECURITY_UTILS_GET_DEPT_ID, HTTPCodeMessage.UNAUTHORIZED.getCode());
        }
    }

    /**
     * 获取用户账户
     **/
    public static String getUsername() {
        try {
            return getLoginUser().getUsername();
        } catch (Exception e) {
            throw new ServiceException(SECURITY_UTILS, SECURITY_UTILS_GET_USER_NAME, HTTPCodeMessage.UNAUTHORIZED.getCode());
        }
    }

    /**
     * 获取用户
     **/
    public static LoginUserDetail getLoginUser() {
        try {
            return (LoginUserDetail) getAuthentication().getPrincipal();
        } catch (Exception e) {
            throw new ServiceException(SECURITY_UTILS, SECURITY_UTILS_GET_LOGIN_USER, HTTPCodeMessage.UNAUTHORIZED.getCode());
        }
    }

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 设置Authentication
     *
     * @return
     */
    public static void setAuthentication(UsernamePasswordAuthenticationToken authentication) {
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }

    /**
     * 生成BCryptPasswordEncoder密码
     *
     * @param password 密码
     * @return 加密字符串
     */
    public static String encryptPassword(String password) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }

    /**
     * 判断密码是否相同
     *
     * @param rawPassword     真实密码
     * @param encodedPassword 加密后字符
     * @return 结果
     */
    public static boolean matchesPassword(String rawPassword, String encodedPassword) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }

    /**
     * 是否为管理员
     *
     * @param identity 用户ID
     * @return 结果
     */
    public static boolean isAdmin(String identity) {
        return identity != null && identity.equals(UserConstant.IS_ADMIN);
    }
}
